package com.blogspot.ostas.oracle.aq.spring;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class OracleAqQueueListener implements MessageListener {
	static final Logger logger = Logger.getLogger(OracleAqQueueListener.class.getName());
	public static final String SELECTOR_PROPERTY = "appAction";
	private String messageText;
	private String selectorString;

	private boolean sendToActiveMQ;
	
	public boolean isSendToActiveMQ() {
		return sendToActiveMQ;
	}

	public void setSendToActiveMQ(boolean sendToActiveMQ) {
		this.sendToActiveMQ = sendToActiveMQ;
	}

	private JmsTemplate activeMqJmsTemplate;

	public void setActiveMqJmsTemplate(JmsTemplate activeMqJmsTemplate) {
		this.activeMqJmsTemplate = activeMqJmsTemplate;
	}

	public void onMessage(Message message) {
		if (message instanceof TextMessage) {
			try {
				messageText = ((TextMessage) message).getText();
				selectorString = message.getStringProperty(SELECTOR_PROPERTY);
				if (logger.isDebugEnabled()) {
					logger.debug("Selector : "
							+ message.getStringProperty(SELECTOR_PROPERTY));
					logger.debug("AQ_Listener : " + messageText
							+ ". Sending to active mq.... ");
				}
				if(isSendToActiveMQ())
				{
					activeMqJmsTemplate.send(new MessageCreator() {
						@Override
						public Message createMessage(Session session) throws JMSException {
							final TextMessage message = session.createTextMessage();
							message.setText(messageText);
							message.setStringProperty(SELECTOR_PROPERTY,
									selectorString);
							return message;
						}
					});
				}
			} catch (Exception ex) {
				logger.error("Error on OracleAqQueueListener : " + ex);
			}
		} else {
			throw new IllegalArgumentException(
					"Message must be of type TextMessage");
		}
	}
}